package com.jw.system.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jw.system.entity.Customer;
import com.jw.system.entity.Goods;
import com.jw.system.entity.GoodsCategory;
import com.jw.system.entity.User;
import com.jw.system.entity.vo.ContractVO;
import com.jw.system.entity.vo.GoodsVO;
import com.jw.system.mapper.CustomerMapper;
import com.jw.system.mapper.GoodsCategoryMapper;
import com.jw.system.mapper.GoodsMapper;
import com.jw.system.mapper.UserMapper;
import com.jw.system.service.AliOssService;
import com.jw.system.service.ContractService;
import com.jw.utils.CommonUtil;
import com.jw.utils.JwtTokenUtil;
import com.jw.utils.ResourceUtil;
import io.swagger.annotations.Api;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.entity.ContentType;
import org.python.core.PyFunction;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.util.*;

@RestController
@RequestMapping("/wx")
@Api(value = "微信小程序", tags = "微信小程序接口")
public class WxController {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;

    @Autowired
    private ContractService contractService;

    @PostMapping("/login_by_weixin")
    public Object loginByWeixin(HttpServletRequest request) {
        Map<String, Object> obj = new HashMap<String, Object>();
        JSONObject result = null;
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader();) {
            char[] buff = new char[1024];
            int len;
            while ((len = reader.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
            result = JSONObject.parseObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String code = result.getString("code");
        JSONObject object = result.getJSONObject("userInfo");
        // 获得此次登录的用户信息
        JSONObject userInfo = object.getJSONObject("userInfo");

        //获取openid
        UriComponents uriComponents = UriComponentsBuilder
                .fromUriString("https://api.weixin.qq.com/sns/jscode2session?appid=wxf03293357b78fb6b&secret=ee4abfc7e5fed990cf05fb2769459d91&js_code={code}&grant_type=authorization_code").build()
                .expand(code)
                .encode();
        String WX_URL = uriComponents.toString();

        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(WX_URL))
                .build();
        ResponseEntity<String> exchange = new RestTemplate().exchange(requestEntity, String.class);
        String body = exchange.getBody();
        JSONObject jsonObject = JSON.parseObject(body);
        String openid = jsonObject.getString("openid");

        System.out.println("==================");
        System.out.println(openid);
        System.out.println(userInfo);

        Map<String, Object> resultObj = new HashMap<String, Object>();

        QueryWrapper<Customer> customerQueryWrapper = new QueryWrapper<>();
        customerQueryWrapper.eq("openid", openid);
        Customer customer = customerMapper.selectOne(customerQueryWrapper);
        if (customer == null) {
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("openid", openid);
            User user = userMapper.selectOne(userQueryWrapper);
            if (user == null) {
                obj.put("errno", 1);
                obj.put("errmsg", "登录失败，用户未绑定，请联系管理员！");
                return obj;
            } else {
                resultObj.put("token", jwtTokenUtil.generateToken(user.getUsername()));
                userInfo.put("avatarUrl", user.getAvatar());
                userInfo.put("nickName", user.getUsername());
                resultObj.put("userInfo", userInfo);
                resultObj.put("userId", user.getId());
                resultObj.put("userType", 1);
                obj.put("errno", 0);
                obj.put("errmsg", "执行成功");
                obj.put("data", resultObj);
                return obj;
            }
        } else {
            resultObj.put("token", jwtTokenUtil.generateToken(customer.getUsername()));
            userInfo.put("nickName", customer.getUsername());
            resultObj.put("userInfo", userInfo);
            resultObj.put("userId", customer.getId());
            resultObj.put("userType", 0);
            obj.put("errno", 0);
            obj.put("errmsg", "执行成功");
            obj.put("data", resultObj);
            return obj;
        }
    }

    @PostMapping("getCon")
    public Object getConsList(@RequestParam(value = "page", defaultValue = "1") Integer current,
                              @RequestParam(value = "size", defaultValue = "7") Integer size,
                              @RequestParam(value = "userId", required = false) Long userId,
                              @RequestParam(value = "userType", required = false) Integer userType) {
        ContractVO contractVO = new ContractVO();
        Page<ContractVO> contractVOPage = contractService.getConList(current, size, 1, contractVO, userId, userType);
        Map<String, Object> obj = new HashMap<String, Object>();
        Map<String, Object> resultObj = new HashMap<String, Object>();
        resultObj.put("data", contractVOPage.getRecords());
        resultObj.put("totalPages", contractVOPage.getTotal());
        resultObj.put("currentPage", current);
        obj.put("errno", 0);
        obj.put("errmsg", "执行成功");
        obj.put("data", resultObj);
        return obj;
    }

    //合同信息
    @PostMapping("conDetail")
    public Object conDetail(@RequestParam(value = "orderId", required = false) Long conId) {
        System.out.println("1111111111111111");
        ContractVO contractVO = contractService.getConById(conId);
        List<GoodsVO> goodsVOS = contractService.getDetail(1, goodsMapper.selectCount(null), conId, new Goods()).getRecords();
        Map<String, Object> obj = new HashMap<String, Object>();
        Map<String, Object> resultObj = new HashMap<String, Object>();
        resultObj.put("data", contractVO);
        resultObj.put("goods", goodsVOS);
        obj.put("errno", 0);
        obj.put("errmsg", "执行成功");
        obj.put("data", resultObj);
        return obj;
    }

    @RequestMapping("upload")
    public void upload(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile[] files) throws IOException {
        Map<String, Object> map = new HashMap<>();
        List<String> list = new ArrayList<>();
        File fileDir = new File("/Users/chenjiwei/Pictures/original");
        if (!fileDir.exists()) {
            //如果没有目录应该创建目录
            fileDir.mkdirs();
        }
        for (int i = 0; i < files.length; i++) {
            MultipartFile mfile = files[i];
            //获取文件后缀
            String imgName = mfile.getOriginalFilename();
            String path = "/Users/chenjiwei/Pictures/original/" + imgName;
            //文件实现上传
            mfile.transferTo(new File(path));
            list.add(path);
        }

        //存放处理后图片的文件夹
        String outPath = "/Users/chenjiwei/Pictures/out";
        List<String> outList = new ArrayList<>();
        File fileDir2 = new File(outPath);
        if (!fileDir2.exists()) {
            //如果没有目录应该创建目录
            fileDir2.mkdirs();
        }
        for (String path : list) {
            String a =UUID.randomUUID().toString().substring(0, 16);
            String out = "/Users/chenjiwei/Pictures/out" + "/" + a + ".png";
            outList.add(out);
            String[] args = new String[]{"python3", "/Users/chenjiwei/PycharmProjects/warpPerspective/warpPerspective.py", String.valueOf(path), String.valueOf(out)};
            Runtime.getRuntime().exec(args);// 执行py文件
        }



        //将处理后的图片合成pdf
        File fileDir3 = new File("/Users/chenjiwei/Pictures/outPdf");
        if (!fileDir3.exists()) {
            //如果没有目录应该创建目录
            fileDir3.mkdirs();
        }

        String pdfPath = "/Users/chenjiwei/Pictures/outPdf/"+UUID.randomUUID().toString().substring(0, 5)+".pdf";

//        String[] args2 = new String[]{"python3", "/Users/chenjiwei/PycharmProjects/warpPerspective/createPDF.py", String.valueOf(outPath), String.valueOf(pdfPath)};
//
//        Runtime.getRuntime().exec(args2);// 执行py文件

        //读取处理好的pdf
        System.out.println(pdfPath);
        File file = new File("/Users/chenjiwei/Pictures/outPdf");
        File[] fileList = file.listFiles();
        File pdf = new File("/Users/chenjiwei/Pictures/outPdf/0b84a.pdf");
        System.out.println(pdf);
        FileInputStream fileInputStream = null;
        fileInputStream = new FileInputStream(pdf);
        System.out.println("hahahahahahahaha");
        MultipartFile multipartFile = new MockMultipartFile(file.getName(), pdf.getName(),
                ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
        contractService.upload(1L,multipartFile);

        //删除out
//        for(String out:outList){
//            File img = new File(out);
//            img.delete();
//        }
//        fileDir2.delete();

        //删除original
//        for(String original : list){
//            File img = new File(original);
//            img.delete();
//        }
//        fileDir.delete();

        //删除pdf

    }

    @PostMapping("catalog")
    public Object catalog() {
        QueryWrapper<GoodsCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid",0);
        List<GoodsCategory> catList = goodsCategoryMapper.selectList(queryWrapper);
        QueryWrapper<GoodsCategory> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("pid",1);
        List<GoodsCategory> catList2 = goodsCategoryMapper.selectList(queryWrapper2);
        Map<String, Object> obj = new HashMap<String, Object>();
        Map<String, Object> resultObj = new HashMap<String, Object>();
        resultObj.put("goodsCount", goodsMapper.selectCount(null));
        resultObj.put("categoryList", catList);
        resultObj.put("currentCategory", catList2);
        obj.put("errno", 0);
        obj.put("errmsg", "执行成功");
        obj.put("data", resultObj);
        return obj;
    }

    @PostMapping("current")
    public Object current(@RequestParam(value = "id", required = false) Long id) {
        QueryWrapper<GoodsCategory> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("pid",id);
        List<GoodsCategory> catList2 = goodsCategoryMapper.selectList(queryWrapper2);
        Map<String, Object> obj = new HashMap<String, Object>();
        Map<String, Object> resultObj = new HashMap<String, Object>();
        resultObj.put("currentCategory", catList2);
        obj.put("errno", 0);
        obj.put("errmsg", "执行成功");
        obj.put("data", resultObj);
        return obj;
    }

    @PostMapping("category")
    public Object category(@RequestParam(value = "id", required = false) Long id) {
        GoodsCategory cat = goodsCategoryMapper.selectById(id);
        QueryWrapper<GoodsCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid",cat.getPid());
        List<GoodsCategory> catList = goodsCategoryMapper.selectList(queryWrapper);

        Map<String, Object> obj = new HashMap<String, Object>();
        Map<String, Object> resultObj = new HashMap<String, Object>();
        resultObj.put("brotherCategory", catList);
        resultObj.put("currentCategory", cat);
        obj.put("errno", 0);
        obj.put("errmsg", "执行成功");
        obj.put("data", resultObj);
        return obj;
    }

    @PostMapping("goodsList")
    public Object getGoodsList(@RequestParam(value = "categoryId", required = false) Long id) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("two_cat_id",id);
        List<Goods> goodsList = goodsMapper.selectList(queryWrapper);

        Map<String, Object> obj = new HashMap<String, Object>();
        Map<String, Object> resultObj = new HashMap<String, Object>();
        resultObj.put("goodsList", goodsList);
        obj.put("errno", 0);
        obj.put("errmsg", "执行成功");
        obj.put("data", resultObj);
        return obj;
    }

    @PostMapping("goodsDetail")
    public Object goodsDetail(@RequestParam(value = "id", required = false) Long id) {
        Map<String, Object> obj = new HashMap<String, Object>();
        Map<String, Object> resultObj = new HashMap<String, Object>();
        resultObj.put("info", goodsMapper.selectById(id));
        obj.put("errno", 0);
        obj.put("errmsg", "执行成功");
        obj.put("data", resultObj);
        return obj;
    }


}
